package com.jnxx.task.controller;

import com.jnxx.basic.query.PageInfo;
import com.jnxx.basic.util.AjaxResult;
import com.jnxx.task.domain.Task;
import com.jnxx.task.domain.Taskandstaff;
import com.jnxx.task.mapper.TaskMapper;
import com.jnxx.task.mapper.TaskandstaffMapper;
import com.jnxx.task.query.TaskQuery;
import com.jnxx.task.service.ITaskService;
import com.ruoyi.common.annotation.Anonymous;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* 后端接口类；
*/
@Slf4j
@Anonymous
@RestController
@RequestMapping("/api/task")
public class TaskController {

    @Autowired
    public ITaskService taskService;

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private TaskandstaffMapper taskandstaffMapper;

    /**
     * 接口：添加或修改
     * @param taskMap  传递的实体
     * @return AjaxResult 响应给前端
     */
//    @PutMapping
//    public AjaxResult addOrUpdate(@RequestBody Task task){
//        if( task.getId()!=null){
//		    taskService.update(task);
//        }else{
//            task.setTaskProgress("0%");
//            taskService.add(task);
//	}
//        return new AjaxResult();
//    }
      @PutMapping
      public AjaxResult addOrUpdate(@RequestBody Map<String, Task> taskMap){
          Task task = taskMap.get("task");
//              if (Integer.parseInt(task.getTaskProgress()) > 100 || Integer.parseInt(task.getTaskProgress()) < 0){
//                  throw new GlobalException(GlobalExceptionEnum.ERROR);
//              }
//              task.setTaskProgress(task.getTaskProgress() + "%");
          if( task.getId()!=null){
            taskService.update(task);
          }else{
              task.setTaskProgress("0");
              task.setStates(false);
              taskService.add(task);
         }
          return new AjaxResult(); 
      }

    /**
    * 接口：删除
    * @param id
    * @return AjaxResult 响应给前端
    */
    @DeleteMapping("/{id}")
    public AjaxResult del(@PathVariable("id") Long id){
        taskService.del(id);
        return new AjaxResult();
    }

    /**
    * 接口：批量删除
    * @param ids
    * @return AjaxResult 响应给前端
    */
    @PatchMapping
    public AjaxResult batchDel(@RequestBody List<Long> ids){
        taskService.batchDel(ids);
        return new AjaxResult();
    }

    /**
    * 接口：查询单个对象
    * @param id
    */
    @GetMapping("/{id}")
    public Task findOne(@PathVariable("id")Long id) {
        return taskService.findOne(id);
    }


    /**
    * 接口：查询所有
    * @return
    */
    @GetMapping
    public List<Task> findAll() throws UnsupportedEncodingException {
        return taskService.findAll();
    }

   /**
    * 接口：分页查询或高级查询
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping
    public PageInfo<Task> page(@RequestBody TaskQuery query) {
        return taskService.page(query);
    }

    /**
     * 通过员工id和开始时间查询任务
     * @param taskMap
     * @return
     */
    @PostMapping("/getStaffTask")
    public HashMap<String, List<Task>> getStaffTask(@RequestBody Map<String, Task> taskMap){
        Task task = taskMap.get("task");
        return taskService.getStaffTaskById(task);
    }

    /**
     * 改变状态，勾选之后
     * @param taskMap
     * @return
     */
    @PutMapping("/changeStates")
    public AjaxResult changeStates(@RequestBody Map<String, Task> taskMap){
        Task task = taskMap.get("task");
        task.setTaskProgress("100");
        task.setFinishTime(new Date());
        taskService.changeStates(task);
        return AjaxResult.success("完成任务");
    }

    /**
     * 一键提醒完成任务
     * @param id
     * @return
     */
    @GetMapping("/reminderTask/{id}")
    public AjaxResult reminderTask(@PathVariable("id") Long id){
        taskService.reminderTask(id);
        return new AjaxResult();
    }

    /**
     * 查询当前登录人的延期任务
     * @param taskMap
     * @return
     */
    @PostMapping("/selectDelayTask")
    public HashMap<String, List<Task>> selectDelayTask(@RequestBody Map<String, Task> taskMap){
        Task task = taskMap.get("task");
        return taskService.selectDelayTask(task);
    }

    /**
     * 改变状态，勾选之后
     * @param id
     * @return
     */
    @GetMapping("/updatSureState/{id}")
    public AjaxResult updatSureState(@PathVariable("id") Long id){
        taskService.updatSureState(id);
        return new AjaxResult();
    }

    @PostMapping("/successEvaluation")
    public AjaxResult successEvaluation(@RequestBody Map<String, Long> taskMap){
        Long taskId = taskMap.get("taskId");
        Long myStart = taskMap.get("myStart");
        Long leaderStart = taskMap.get("leaderStart");
        taskService.successEvaluation(taskId, myStart, leaderStart);
        return AjaxResult.success();
    }

    /**
     *  发布每日任务
     */
    @Scheduled(cron = "0 0 2 * * MON-FRI")
    public void dailyTaskRelease() {
        LocalDateTime now = LocalDateTime.now();
        String taskType = "每日任务";
        // 获取当前是星期几
        DayOfWeek dayOfWeek = now.getDayOfWeek();
        if (dayOfWeek.equals(DayOfWeek.MONDAY)){
            // 今天是星期一， 获取上周五的日期
            now = now.with(TemporalAdjusters.previous(DayOfWeek.FRIDAY));
        }else {
            // 普通周周二到周五，往前推一天
            now = now.minusDays(1);
        }
        List<Task> taskList = taskMapper.findDailyTask(taskType, now);
        log.info("创建每日任务，参数:{}",taskList);
        initTask(taskList, now, now);
    }

    /**
     *  发布每周任务
     */
    @Scheduled(cron = "0 0 3 * * 1")
    public void weekTaskRelease() {
        LocalDateTime now = LocalDateTime.now();
        String taskType = "每周任务";
        // 获取上周一的日期
        LocalDateTime lastWeekMon = now.with(TemporalAdjusters.previous(DayOfWeek.MONDAY));
        LocalDateTime lastWeekFei = now.with(TemporalAdjusters.previous(DayOfWeek.FRIDAY));
        // 获取上周五的日期
        List<Task> taskList = taskMapper.findWeekTask(taskType, lastWeekMon, lastWeekFei);
        log.info("创建每周任务");
        // 获取本周五的日期
        LocalDateTime plusDays = now.plusDays(4);
        initTask(taskList, now, plusDays);
    }

    /**
     * 初始化任务并发布
     * @param taskList
     */
    private void initTask(List<Task> taskList, LocalDateTime startTimeTmp, LocalDateTime endTimeTmp) {
        // 将 LocalDateTime 转换为 Instant，并从中获取 Date
        Date startTime = Date.from(startTimeTmp.atZone(ZoneId.systemDefault()).toInstant());
        Date endTime = Date.from(endTimeTmp.atZone(ZoneId.systemDefault()).toInstant());

        for (Task task : taskList) {
            // 获取原来的 taskAndStaff
            List<Taskandstaff> byTaskId = taskandstaffMapper.findByTaskId(task.getId());
            // 初始化 task的值，重新添加一条任务
            task.setId(null);
            task.setSureState("1");
            task.setTaskProgress("0");
            task.setStates(false);
            task.setAnnex(null);
            task.setFinishTime(null);
            task.setStartTime(startTime);
            task.setEndTime(endTime);
            task.setMyStart(0L);
            task.setLeaderStart(0L);
            log.info("添加任务，任务数据:{}",task);
            taskService.add(task);
            // 设置新的taskId，设置id为null
            List<Taskandstaff> collect = byTaskId.stream().map(e -> {
                e.setTaskId(Math.toIntExact(task.getId()));
                e.setId(null);
                return e;
            }).collect(Collectors.toList());
            log.info("添加任务参与人员，数据详情:{}",collect);
            // 重新添加
            for (Taskandstaff taskandstaff : collect) {
                taskandstaff.setCreatTime(new Date());
                taskandstaffMapper.add(taskandstaff);
            }
        }
    }

}
